<?php
namespace Common\ORG;

class AttUpload {
    protected $m_res = array('rcode'=>0,'data'=>NULL,'msg'=>'500 Internal Error');

    //获取上传根目录
    public function _root( $with_upload = true )
    {
        $root = __ROOT__ . DIRECTORY_SEPARATOR;
        $www_root = realpath(  $root ).DIRECTORY_SEPARATOR;
        $cfg_upload = $this->config();
        if( $with_upload )
            $www_root = $cfg_upload&&isset( $cfg_upload['DIR'] ) ? $www_root.$cfg_upload['DIR']:'uploads';
        $www_root = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $www_root.DIRECTORY_SEPARATOR );
        if( !is_dir( $www_root )){
            mkdir( $www_root, 0755, true );
        }
        return $www_root;
    }

    //上传参数配置解析
    public function config()
    {
        $cfg_upload = C('UPLOAD');
        //默认配置文件
        $defaults = array(
                        'DIR'=> 'uploads/',
                        'DIR_RULE' => 'Y/md/',
                        'FILE_PREFIX' =>'',
                    );
        if( !$cfg_upload )
            $cfg_upload = array();

        return array_merge($cfg_upload, $defaults );
    }


    /**
    * 使用HTTP_UPLOAD上传文件
    *
    */
    public function http_upload( $_key, $dir = FALSE)
    {
        $res = $this->m_res;
        if (!$_key)
            $res['msg'] = "无法获取上传文件";
        else {
            $res['msg'] = "上传文件发生错误";
            if ( $_FILES && isset($_FILES[$_key]) && $_FILES[$_key]['error'] == 0) {
                $res = $this->upload( $_FILES[$_key]['name'], $_FILES[$_key]['tmp_name'], $dir);
            }
        }
        return $res;
    }


    /**
    * POST 上传接口
    *
    *@param string $name     文件上传的数组key，暂时不支持数组上传
    *@param string $tmp_path 临时文件路径
    *@param string $dir      自定义上传文件目录，根目录在上传目录下面。
    *                        比如 excel=> upload/excel 或者 pdf => upload/pdf
    *
    *@return array( 'rcode' => 1:成功;0:失败,
    *               'msg'   => 提示信息，
    *               'data'  => 文件信息，只有上传成功才有
    *                        array(
    *                            'real_path' => 真实文件路径(全路径)
    *                            'view_path' => 浏览器查看路径，相对路径基于ＵＲＬ访问
    *                            'size'      => 文件大小　Ｂ
    *                            'name'      => 文件保存名称
    *                            'ext'       => 文件类型后缀名
    *                        ) 
    *               )
    */
    public function upload( $name, $tmp_path, $dir = FALSE )
    {
        $res = $this->m_res;
        if( !file_exists( $tmp_path ) ){
            $res['msg'] = "移动临时文件不存在";
        }
        else if( file_exists( $tmp_path) &&  !is_uploaded_file( $tmp_path) ){
            $res['msg'] = "请通过http_post上传文件";
        }
        else{

            $root_path  = $this->_root();
            $cfg_upload = $this->config();
            $newDir = $dir ? $root_path.$dir.DIRECTORY_SEPARATOR : $root_path;
            $dateDir = date( $cfg_upload['DIR_RULE'] );
            $newDir .= $dateDir.DIRECTORY_SEPARATOR;
            $newDir = str_replace('/', DIRECTORY_SEPARATOR, $newDir ); //处理定义规则中路径连接符的问题
            $newDir = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $newDir );
            if( !is_dir( $newDir ) )
                mkdir( $newDir, 0755, true );
            $ext = substr($name,strrpos( $name,'.')+1);
            $ext = strtolower( $ext );

            /*上传图片严格检测*/
            if(in_array($ext, array('gif','jpg','jpeg','bmp','png','swf'))) {
                $imginfo = getimagesize( $tmp_path );
                if(empty($imginfo) || ($ext == 'gif' && empty($imginfo['bits']))){
                    $res['msg'] = '非法图像文件！';
                    return $res;
                }
            }

            $fname = uniqid( $cfg_upload['FILE_PREFIX']).'.'.$ext;
            $newPath = $newDir.$fname;
            if( move_uploaded_file( $tmp_path, $newPath ) ){
                $res['rcode'] = 1;
                $res['msg'] = 'OK';
                $res['data'] = $this->Finfo( $newPath );
                if ($res['data'])
                    $res['data']['source_name'] = $name;
            }
            else{
                $res['msg'] = "移动临时文件失败";
            }
        }

        return $res;
    }

    //获取文件内容信息
    public function Finfo( $_path )
    {
        $info = false;

        if( file_exists( $_path ) ){
            $root = __ROOT__ . DIRECTORY_SEPARATOR;
            $root = realpath(  $root ).DIRECTORY_SEPARATOR;
            $info['real_path'] = $_path;
            $info['view_path'] = '/'.str_replace( $root , '', $_path );
            $info['view_path'] = str_replace('\\','/', $info['view_path']); // 将windows主机替换
            $info['size'] = filesize($_path);
            $info['name'] = basename( $_path );
            $info['ext'] = substr($_path,strrpos( $_path,'.')+1);
        }

        return $info;
    }
}
?>
